package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mf.entity.Dictionary;
import com.mf.exceptions.GraceException;
import com.mf.mapper.DictionaryMapper;

import com.mf.service.IDictionaryService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author mf
 * @since 2024-06-08
 */
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {
    @Resource
    private DictionaryMapper dictionaryMapper;

    /**
     * 根据编号查询数据字典
     *
     * @param code 编号多个以逗号分隔
     * @return 数据字典集合
     */
    @Override
    public List<Dictionary> findByCode(String code) {
        final String[] strings = code.split(",");
        final LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dictionary::getCode, Arrays.asList(strings));
        return dictionaryMapper.selectList(queryWrapper);
    }

    /**
     * 新增数据字典
     * @param dictionary 数据字典实体类
     * @return 添加成功返回1，否则返回0
     */
    @Override
    @Transactional
    public Integer add(Dictionary dictionary) {
        final LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        if(dictionary.getPid() == 0 ){
            if(dictionary.getCode() == null || StringUtils.isBlank(dictionary.getCode())){
                GraceException.display("顶级节点必须有编号");
                return null;
            }
            queryWrapper.eq(Dictionary::getCode,dictionary.getCode());
        }
        queryWrapper.eq(Dictionary::getValue,dictionary.getValue());
        if(dictionaryMapper.selectCount(queryWrapper) > 0){
            GraceException.display("值不能重复");
            return null;
        }

        return dictionaryMapper.insert(dictionary);
    }
}
